package com.zr.config;

import com.zr.dao.order.OrderFormDao;
import com.zr.utils.RedisUtil;
import com.zr.utils.SequenceUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 订单编号初始化存储到redis中
 * @author huangguilong
 */
@Component
public class SequenceInitRunner implements ApplicationRunner {

    @Resource
    private SequenceUtil sequenceUtil;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private OrderFormDao orderFormDao;

    // 注入订单编号前缀
    @Value("${orderId.prefix}")
    private String orderIdPrefix;

    /**
     * @param args
     * @throws Exception
     * @author huangguilong
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String todayNo = sdf.format(new Date());
        //查询当日最后一个订单编号
        String lastOrderId = orderFormDao.getLastOrderId(todayNo);
        int n = 0;
        if (StringUtils.hasLength(lastOrderId)) {
            String code = lastOrderId.substring(10);
            n = Integer.parseInt(code);
        }
        String key = orderIdPrefix + todayNo;
        //移除key
        redisUtil.remove(key);
        //初始化key
        sequenceUtil.incr(key, n);
    }
}
